<?php

namespace App\Services;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class AliyunLive
{
    private $error;
    const DOMAIN_NAME='live.lmyqaq.top';//你的加速域名，和推流域名一致。
    const REGION_ID='cn-shanghai';//区域
    const ACCESS_KEY_ID='LTAI5tDm3aMV9R7HwWDBwycM';//阿里云秘钥
    const ACCESS_KEY_SECRET='TNoWPjZgOhM0HiZZ4KWkl0e0Ki5ixe';//阿里云秘钥
    const LIVE_HOST='live.lmyqaq.top';//写死，阿里云直播CDN域名
    const ALIVE_URL='live.lmyqaq.top';//推域名
    const ALIVE_KEY='Lmy2949523574com';//推流鉴权KEY，后台拿
    const TLIVE_URL='push.lmyqaq.top';//关联的播域名
    const TLIVE_KEY='push2949523574com';    //播流鉴权KEY，后台拿

    /**
     * 创建签名
     * @param $path 播放地址 域名后面所有
     * @param $exp //结束时间
     * @param $key
     * @return string
     */
    private static function createSign($path,$exp,$key)
    {
        $rand=0;
        $uid=0;
        $str=sprintf("%s-%s-%s-%s-%s",$path,(string)$exp,(string)$rand,(string)$uid,$key);
        $hashValue=md5($str);
        $authKey=sprintf("%s-%s-%s-%s",(string)$exp,(string)$rand,(string)$uid,$hashValue);
        return "auth_key=$authKey";
    }

    /**
     * 创建是直播地址
     * @param $appName 应用名称 ，自定义
     * @param $streamName 房间名称，自定义，该应用下唯一
     * @param $endTime 结束时间
     * @return array|bool  播放流（观看者）：alive_url，推流（直播者）：tlive_url
     */
    public static function createdLive($appName,$streamName,$endTime)
    {
        if(!$appName || !$streamName || !$endTime || $endTime < time()){
            return false;
        }
        //创建播流
        $path="/$appName/$streamName";
        $aliveUrl='rtmp://'.self::ALIVE_URL."$path?".self::createSign($path,$endTime,self::ALIVE_KEY);

        //创建推流
        $push_path="/$appName/$streamName".'.m3u8';
        //$tliveUrlRTMP= 'rtmp://'.self::TLIVE_URL."$path?".self::createSign($path,$endTime,self::TLIVE_KEY);
        // $tliveUrlFLV ='http://'.self::TLIVE_URL."$path.flv?".self::createSign($path,$endTime,self::TLIVE_KEY);
        $tliveUrlM3U8='http://'.self::TLIVE_URL."$path.m3u8?".self::createSign($push_path,$endTime,self::TLIVE_KEY);

        return [
            'alive_url'=>$aliveUrl,
            'tlivem3u8_url'=>$tliveUrlM3U8,
        ];
    }
    //停止直播
    public static function stopLive($appName,$streamName)
    {

        $query=[
            'RegionId' => self::REGION_ID,
            'AppName' => $appName,
            'StreamName' => $streamName,
            'LiveStreamType' => "publisher",
            'DomainName' => self::DOMAIN_NAME,
            // 'ResumeTime'=>'',
        ];
        $_this=new static();
        $result=$_this->request('ForbidLiveStream',$query);
        return true;
    }
    //恢复直播
    public static function resumeLive($appName,$streamName)
    {
        $query=[
            'RegionId' => self::REGION_ID,
            'LiveStreamType' => "publisher",
            'AppName' => $appName,
            'StreamName' => $streamName,
            'DomainName' => self::DOMAIN_NAME,
        ];
        $_this=new static();
        $result=$_this->request('ResumeLiveStream',$query);
        return true;
    }

    //获取直播在线人数
    public static function getOnlineUserNum($appName,$streamNma)
    {

        $query=[
            'RegionId' => self::REGION_ID,
            'DomainName' => self::DOMAIN_NAME,
            'AppName'=>$appName,
            'StreamName' =>$streamNma,
        ];
        $_this=new static();
        $result=$_this->request('DescribeLiveStreamOnlineUserNum',$query);
        return $result;
    }



    //日志
    public function log($msg,$info='info')
    {
        $msg='直播接口：'.$msg.($info !='info'?var_export($info,1):'');
        log_write($msg);
    }
    //获取错误
    public static function getError()
    {
        return (new static())->error;
    }
    //请求
    private function request($action,Array $query)
    {
        AlibabaCloud::accessKeyClient(self::ACCESS_KEY_ID, self::ACCESS_KEY_SECRET)
            ->regionId(self::REGION_ID)
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('live')
                // ->scheme('https') // https | http
                ->version('2021-10-28')
                ->action($action)
                ->method('POST')
                ->host(self::LIVE_HOST)
                ->options([
                    'query' => $query,
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            $this->error=$e->getMessage();
            return false;
        } catch (ServerException $e) {
            $this->error=$e->getMessage();
            return false;
        }
    }
}
